<?php
	# connection to localhost
	$db_host = "localhost";
	//$db_passwd = "enc130221db";
	//$db_user = "kippco";
	//$db_name = "kippco";
	$db_host = "localhost";
	$db_user = "root";
	$db_passwd = "ayaxyz1425gg";
	$db_name = "ggoggo";
	define('MYSQL_HOST',            $db_host);
	define('MYSQL_USER',            $db_user);
	define('MYSQL_PASS',            $db_passwd);
	define('MYSQL_NAME',            $db_name);
	$conn = mysqli_connect(MYSQL_HOST,MYSQL_USER,MYSQL_PASS,MYSQL_NAME);
	mysqli_query($conn, "set names utf8");

	# DB



	class Validation {
		public static function check_is_null($arr_val, $message){
			if(empty($arr_val)){
				echo "<script>alert(\"".$message."\");</script>";
			}
		}
	}




	class Nmysql extends mysqli {
			private $host;
			private $user;
			private $passwd;
			private $dbname;

			private $latest_query = array();

			public function __construct(){
					$mysqli = new mysqli();

					$this->host             = MYSQL_HOST;
					$this->user             = MYSQL_USER;
					$this->passwd   = MYSQL_PASS;
					$this->dbname   = MYSQL_NAME;
					parent::__construct($this->host, $this->user, $this->passwd, $this->dbname);

					# 연결되지 않았을 경우
					if(mysqli_connect_error()){
							die('Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error());
					}

					# 문자셋
					//$chrset = parent::character_set_name();
					//if(strcmp($chrset,'utf8')) parent::set_charset(str_replace('-','',_CHRSET_));
					parent::query("set names utf8");

			}




			####################################################
			# public method                                    #
			####################################################

//              public function execute($query = NULL){
//                      $this->flush();
//                      $query = trim($query);
//                      $this->last_query = $query;
//                      $this->affected_row = $this->db->exec($query);
//                      if ( $this->catch_error() ) return false;
//                      return $this->affected_row;
//              }

			# 데이터 베이스의 데이터를 배열로 리턴 (result array)
			# res >> results
			# cnt >> count
			# has >> 데이터 존재 여부
			#
			#       example)
			#               $article = $db->gets(sprintf("SELECT * FROM `fruits`"), 'puts');
			#               $article = $db->gets(sprintf("SELECT fuid, name, name_eng, enable FROM `fruits`"), 'puts');
			#       출력 >> Array
			#               (
			#                       [res] => Array
			#                               (
			#                                       [0] => Array
			#                                               (
			#                                                       [fuid] => 1
			#                                                       [name] => 오렌지
			#                                                       [name_eng] => orange
			#                                                       [enable] => Y
			#                                               )
			#
			#                                               )
			#
			#                                       ...
			#
			#                                       [10] => Array
			#                                               (
			#                                                       [fuid] => 11
			#                                                       [name] => 구아바
			#                                                       [name_eng] => Guava
			#                                                       [enable] => Y
			#                                               )
			#
			#                               )
			#
			#                       [cnt] => 11
			#                       [has] => 1
			#               )
			public function gets($query=NULL, $data_print='') {
					$this->latest_query[] = $query;
					preg_match("/[*]/i", $query, $matches);
					$result_arr = array();
					if(@$matches[0] == '*'){
							# 리스팅
							$res = parent::query($query);
							while ($row = $res->fetch_array(MYSQLI_ASSOC)){
									//Nlog::puts(count($row));
									$result_arr['res'][] = $row;
							}

							# 카운팅
							$query = preg_replace("/[*]/i", "count(*)", $query);
							//Nlog::puts("original query",$query);

							# LIMITED SELECT COUNT(*)
							$ismatch = preg_match("/LIMIT (.*?), (.*?);/",$query);
							if($ismatch) {
									$query = preg_replace("/FROM /", "FROM (SELECT 1 FROM ", $query);
									$query = preg_replace("/ORDER BY `(.*?)` (DESC|ASC)/", "", $query);
									$ismatche = preg_match("/LIMIT (.*?), (.*?);/", $query);
									$query = preg_replace("/;/","",$query);
									if($ismatche){
											$query .= ") cnt;";
									}
									//Nlog::puts("match!, converted query",$query);
									# SELECT COUNT(*) FROM (SELECT 1 FROM `ggo_cfg_packages_pref` LIMIT 10, 10) cnt;
							}
							$cnt = parent::query($query)->fetch_row();

							//Nlog::puts('cnt', $cnt);
							$result_arr['cnt'] = $cnt[0];

							# 데이터가 존재 여부.
							#if($result_arr['cnt'] > 0){
							#        $result_arr['has'] = TRUE;
							#} else {
							#        $result_arr['res'] = array();
							#        $result_arr['has'] = FALSE;
							#}

							///*/
							# 데이터 존재 여부
							#if( count($result_arr['cnt']) > 0 ){
							#        $result_arr['has'] = TRUE;
							#} else {
							#        $result_arr['res'] = array();
							#        $result_arr['has'] = FALSE;
							#}
							//*/

							$ret = $result_arr;
					} else {
							# 리스팅
							$res = parent::query($query);
							while ($row = $res->fetch_array(MYSQLI_ASSOC)){
									$result_arr['res'][] = $row;
							}

							# 카운팅
							$cnt = parent::num_rows;
							$result_arr['cnt'] = $cnt;

							# 데이터가 존재 여부.
							if($cnt > 0){
									$result_arr['has'] = TRUE;
							} else {
									$result_arr['has'] = FALSE;
							}

							# 데이터 존재 여부
							if(count($result_arr['cnt']) > 0){
									$result_arr['has'] = TRUE;
							} else {
									$result_arr['has'] = FALSE;
							}

							$ret =  $result_arr;
					}

					# 데이터를 찍어 볼 것인가.
					if($data_print != ''){
							if($data_print == 'puts') {
									Nlog::puts($ret);
							} elseif($data_print == 'puts') {
									Nlog::puts($ret);
							} else {
									echo "<puts>"; print_r($ret); echo "</puts>";
							}
					}
					return $ret;
			}


			# 데이터 베이스의 데이터를 배열로 리턴 (row array)
			# res >> row
			# cnt >> count
			# has >> 데이터 존재 여부
			#
			#       example)
			#               $article = $db->get(sprintf("SELECT * FROM `fruits` WHERE `fuid`= '3'"), 'puts');
			#               $article = $db->get(sprintf("SELECT fuid, name, name_eng, enable FROM `fruits` WHERE `fuid`= '1'"), 'puts');
			#       출력 >> Array
			#               (
			#                       [res] => Array
			#                               (
			#                                       [fuid] => 1
			#                                       [name] => 오렌지
			#                                       [name_eng] => orange
			#                                       [enable] => Y
			#                               )
			#
			#                       [cnt] => 1
			#                       [has] => 1
			#               )
			public function get($query=NULL, $data_print='') {
					$this->latest_query[] = $query;
					$result_arr = array();
					if(preg_match("/[*]/i", $query)){
							# 리스팅
							$res = parent::query($query)->fetch_array(MYSQLI_ASSOC);
							$result_arr['res'] = $res;

							# 카운팅
							$query = preg_replace("/[*]/i", "count(*)", $query);
							$cnt =  parent::query($query)->fetch_row();
							$result_arr['cnt'] = $cnt[0];

							# 데이터 존재 여부.
							if($result_arr['cnt'] > 0){
									$result_arr['has'] = TRUE;
							} else {
									$result_arr['has'] = FALSE;
							}

							$ret = $result_arr;
					} else {
							# 리스팅
							$res = parent::query($query);
							while ($row = $res->fetch_array(MYSQLI_ASSOC)){
									$result_arr['res'] = $row;
							}

							# 카운팅, 데이터 존재 여부.
							if(is_array($result_arr['res']) == TRUE){
									$result_arr['cnt'] = 1;
									$result_arr['has'] = TRUE;
							} else {
									$result_arr['cnt'] = 0;
									$result_arr['has'] = FALSE;
							}

							$ret =  $result_arr;
					}

					# 데이터를 찍어 볼 것인가.
					if($data_print != ''){
							if($data_print == 'puts') {
									Nlog::puts($ret);
							} elseif($data_print == 'puts') {
									Nlog::puts($ret);
							} else {
									echo "<puts>"; print_r($ret); echo "</puts>";
							}
					}
					return $ret;
			}


			# 데이터 베이스의 데이터를 배열로 리턴 (one data)
			# *** >> one data
			# cnt >> count
			# has >> 데이터 존재 여부
			#
			#       example)
			#               $article = $db->getone(sprintf("SELECT `name` FROM `fruits` WHERE `fuid`= 1"), 'puts');
			#       출력 >>
			#       Array
			#       (
			#               [name] => 오렌지
			#               [cnt] => 1
			#               [has] => 1
			#       )
			public function getone($query=NULL, $data_print='') {
					$this->latest_query[] = $query;
					$res = parent::query($query)->fetch_array(MYSQLI_ASSOC);
					$result_arr['res'] = $res;
					$result_arr = $res;

					# 카운팅, 데이터 존재 여부.
					if(is_array($result_arr) == TRUE){
							$result_arr['cnt'] = 1;
							$result_arr['has'] = TRUE;
					} else {
							$result_arr['cnt'] = 0;
							$result_arr['has'] = FALSE;
					}
					$ret = $result_arr;

					# 데이터를 찍어 볼 것인가.
					if($data_print != ''){
							if($data_print == 'puts') {
									Nlog::puts($ret);
							} elseif($data_print == 'puts') {
									Nlog::puts($ret);
							} else {
									echo "<puts>"; print_r($ret); echo "</puts>";
							}
					}
					return $ret;
			}

			# 전체 카운트를 얻는다
			public function getcnts($table_name, $data_print='') {
					$ret = parent::query(sprintf("SELECT count(*) as cnts FROM %s", $table_name))->fetch_array(MYSQLI_ASSOC);
					if($data_print != ''){
							if($data_print == 'puts') {
									Nlog::puts($ret);
							} elseif($data_print == 'puts') {
									Nlog::puts($ret);
							} else {
									echo "<puts>"; print_r($ret); echo "</puts>";
							}
					}
					return $ret['cnts'];
			}

			# 마지막 쿼리를 출력
			#       example)
			#               Nlog::puts($db->get_latest_query());
			#       출력 >>
			#               Array
			#               (
			#                       [0] => SELECT package_filename, package_desc FROM `ggo_cfg_packages` WHERE package_file = 'admin.package.process.php';
			#                       [1] => UPDATE `ggo_cfg_packages` SET `package_filename` = '부트캠프12', `package_desc` = '꼬꼬 프레임워크의 시작점 입니다.' WHERE `puid` = 3;
			#                       [2] => UPDATE `ggo_cfg_packages` SET `package_filename` = '로그인12', `package_desc` = '로그인' WHERE `puid` = 2;
			#                       [3] => UPDATE `ggo_cfg_packages` SET `package_filename` = '로그인 처리12', `package_desc` = '로그인 처리' WHERE `puid` = 1;
			#               )
			public function get_latest_query($data_print='') {
					$ret = $this->latest_query;
					if($data_print != ''){
							$ret = "latest query >> " . $ret;
							if($data_print == 'puts') {
									Nlog::puts($ret);
							} elseif($data_print == 'puts') {
									Nlog::puts($ret);
							} else {
									echo "<puts>"; print_r($ret); echo "</puts>";
							}
					} else {
							return $ret;
					}
			}


			# 새로운 열을 삽입/수정/삭제, 영향받은 결과를 배열로 리턴.
			# affected >> 결과
			# has >> affected가 1보다 클시 TRUE
			public function que($query=NULL, $data_print='') {
					$this->latest_query[] = $query;
					$res = parent::query($query);
					$result_arr['affected'] = $this->affected_rows;
					if($result_arr['affected'] > 0){
							$result_arr['has'] = TRUE;
					} else {
							$result_arr['has'] = FALSE;
					}
					$ret = $result_arr;
					//echo self::affected_rows;

					# 데이터를 찍어 볼 것인가.
					if($data_print != ''){
							if($data_print == 'puts') {
									Nlog::puts($ret);
							} elseif($data_print == 'puts') {
									Nlog::puts($ret);
							} else {
									echo "<puts>"; print_r($ret); echo "</puts>";
							}
					}
					return $ret;
			}


			# 일반적인 mysqli::query를 사용하나 마지막 쿼리를 찍어볼 수 있다는 장점이 있다.
			public function q($query=NULL, $get_result = TRUE) {
					$this->latest_query[] = $query;
					$res = parent::query($query);
					if($get_result) {
							while ($row = $res->fetch_array(MYSQLI_ASSOC)){
									$result_arr[] = $row;
							}
							$ret = $result_arr;
							return $ret;
					}
			}

			#fetch.
			public function fa($res){
					if(is_resource($res)){
							$ret = $res->fetch_array(MYSQLI_ASSOC);
							return $ret;
					}
			}

			####################################################
			# meta database info                               #
			####################################################

			public function field_names($table_name, $data_print=FALSE) {

					$result_arr = array();
					$result = parent::query( "DESC $table_name" );
					while ($row = $result->fetch_array()) {
							$result_arr[] = $row[0];
					}

					if($data_print == TRUE){
							echo "<puts>";
							print_r($result_arr);
							echo "</puts>";
					}

					return $result_arr;
			}

			public function get_comment($table_name, $data_print=FALSE) {
					$result_arr = array();
					$result = parent::query( "SELECT `COLUMN_COMMENT` FROM information_schema.COLUMNS WHERE `TABLE_NAME` = '{$table_name}'" );
					while ($row = $result->fetch_array()) {
							$result_arr[] = $row['COLUMN_COMMENT'];
					}

					if($data_print == TRUE){
							echo "<puts>";
							print_r($result_arr);
							echo "</puts>";
					}

					return $result_arr;
			}

			# 테이블 생성여부 체크
			public function tablecheck($table,$db) {
					$result = mysql_list_tables($db);
					for($i = 0;$i < mysql_num_rows($result);$i++) {
							if($table == mysql_tablename($result,$i)) return true;
					}
					return false;
			}
			public function get_table_comment($table_name, $data_print=FALSE) {
					$result = $this->gets("SHOW TABLE STATUS LIKE '{$table_name}'");
					return $result[0]['Comment'];
			}

			public function __destruct(){
					//parent::close();
			}
	}









	####################################################
	# Pagenation 리스트 페이지네이션 함수              #
	####################################################

	class Pagenation {

			# 페이지네이션
			#
			# example)
			#       $pagenation_cfg = array(
			#               'uri'                           => "ncrud_list.php",
			#               'articles_count'        => 20,
			#               'req_page'                      => empty($req['p1'])? 0 : $req['p1'],
			#               'page_size'                     => 6,
			#               'articles_cnt'          => $db->getcnts($ncrud['table_name']),
			#               'style'                         => Pagenation::$style_default,
			#               'get'                           => 'p1'
			#       );
			#       $article = $db->gets(
			#               sprintf("SELECT * FROM `%s` ORDER BY buid DESC LIMIT %s, %s ",
			#                       $ncrud['table_name'],
			#                       $pagenation_cfg['req_page'] * $pagenation_cfg['articles_count'],
			#                       $pagenation_cfg['articles_count']
			#               )
			#       );
			#       $pagenation = Pagenation::out($pagenation_cfg);
			#
			#


			public static $style_default = "
					<style type=\"text/css\">
							.pagenation_prev{padding: 0 5px 0 5px;height:20px;margin:2px;cursor:pointer;}
							.pagenation_curr{padding: 0 5px 0 5px;height:20px;margin:2px;font-weight:bold;}
							.pagenation_link{padding: 0 5px 0 5px;height:20px;margin:2px;cursor:pointer;}
							.pagenation_next{padding: 0 5px 0 5px;height:20px;margin:2px;cursor:pointer;}
					</style>
			";

			public static $style_white = "
					<style type=\"text/css\">
							.pagenation_prev{background-color:#F1F1F1;padding: 2px 10px 2px 10px;height:30px;border:1px solid #C2C4CA;margin:2px;color:#999999;cursor:pointer;}
							.pagenation_curr{background-color:#FFFFFF;padding: 2px 10px 2px 10px;height:30px;border:1px solid #C2C4CA;margin:2px;color:#484848;font-weight:bold;}
							.pagenation_link{background-color:#F1F1F1;padding: 2px 10px 2px 10px;height:30px;border:1px solid #C2C4CA;margin:2px;color:#999999;cursor:pointer;}
							.pagenation_next{background-color:#F1F1F1;padding: 2px 10px 2px 10px;height:30px;border:1px solid #C2C4CA;margin:2px;color:#999999;cursor:pointer;}
					</style>
			";

			public static function out($pagenation_cfg){

					$uri                            = $pagenation_cfg['uri'];            # 이동할 URL
					$articles_page          = $pagenation_cfg['articles_count']; # 한페이지에 보여줄 레코드 수
					$page                           = $pagenation_cfg['req_page'];       # 현재 페이지
					$total                          = $pagenation_cfg['articles_cnt'];   # 한페이지에 보여줄 갯수
					$page_size                      = $pagenation_cfg['page_size'];      # 전체 레코드 수
					$style                          = $pagenation_cfg['style'];          # 스타일
					$get                            = $pagenation_cfg['get'];            # 기준 $_GET키 이름

					$prt_first_page = NULL;
					$pt_page = NULL;
					$prt_end_page = NULL;

					if(strpos($uri,'?') === false) {
							$uri .= "?";
					} else {
							$uri .= "&";
					}

					//echo $uri;
					//echo $get;
					if(strpos($uri,$get) === true){
							//echo $uri;
					}

					if($total > 0){
							$total_page = intval(($total-1)/$articles_page);
							if (!$page) {
									$now_page = 0;
							} else {
									$now_page = $page;
							}
							$start_rec = ($now_page) * $articles_page;
							if (($start_rec+$articles_page)>$total) {
									$end_rec = $total;
							} else {
									$end_rec = $start_rec + $articles_page;
							}
							$first_page = intval($now_page/$page_size)*$page_size;

							if (($first_page+($page_size-1))>$total_page) {
									$last_page = $total_page;
							} else {
									$last_page = $first_page+($page_size-1);
							}

							if($first_page == 0) {
									$pt_page = "";
							} else {
									$prt_first_page = sprintf("<a href='%s%s=0'>[1]</a>...",$uri,$get);
									$prev_page = $first_page - 1;
									$pt_page = sprintf("<a href='%s%s=%s'><span class='pagenation_prev'>◀ %s</span></a> ",$uri,$get,$prev_page, '이전');
							}

							for ($j=$first_page; $j<=$last_page; $j++) {
									$dis_page = $j + 1;
									if ($j == $now_page) {
											$pt_page .= sprintf("<span class='pagenation_curr'>%s</span>",$dis_page);
									} else {
											$pt_page .= sprintf("<a href='%s%s=%s'><span class='pagenation_link'>%s</span></a>",$uri,$get,$j,$dis_page);
									}
							}
							if ($last_page != $total_page) {
									$next_page = $first_page+$page_size;
									$pt_page .= sprintf(" <a href='%s%s=%s'><span class='pagenation_next'>%s ▶</span></a>",$uri,$get,$next_page, '다음');
									$prt_end_page = sprintf("...<a href='%s%s=%s'>[%s]</a>",$uri,$total_page,$total_page+1);
							} else {
									$pt_page .= "";
							}


							$dis_now_page = $now_page + 1;
							$dis_total_page = $total_page + 1;

							$pt_page = sprintf("%s<table width=\"100%%\" cellpadding=\"0\" cellspacing=\"0\"><tr><td align=\"center\" style=\"text-align:center\">%s</td></tr></table>", $style, $prt_first_page.$pt_page.$prt_end_page);
			//              return $prt_first_page.$pt_page.$prt_end_page;
							return $pt_page;
					}
			}
	}
?>